import path from "path"
import fs from "fs-extra"
import { randomUUID } from "crypto"
import AdmZip from "adm-zip"
import * as glob from "glob"
import { desktopPath } from "@/utils"

const main = () => {
  const ftpDirPath = path.join(desktopPath, "ftp")

  const options = { windowsPathsNoEscape: true }

  const zipFilePaths = glob.sync(path.join(ftpDirPath, "*.zip"), options)

  zipFilePaths.forEach(zipFilePath => {
    const tmpDir = path.join(__dirname, "tmpDir" + randomUUID())
    const zip = new AdmZip(zipFilePath)
    zip.extractAllTo(tmpDir, true)

    const dirs = glob.sync(path.join(tmpDir, "**/t_*/*/"), options)

    dirs.forEach(file => {
      const targetPath = file.replace(tmpDir, desktopPath)

      fs.moveSync(file, targetPath, { overwrite: true })
    })

    fs.rmSync(tmpDir, { recursive: true, force: true })
    fs.rmSync(zipFilePath, { recursive: true, force: true })
  })
}

export default main
